package com.itboy.framework.web.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itboy.common.core.domain.entity.SysUser;
import com.itboy.common.core.domain.entity.WeChatUser;
import com.itboy.common.core.domain.model.LoginUser;
import com.itboy.common.enums.UserStatus;
import com.itboy.common.exception.BaseException;
import com.itboy.framework.config.properties.WeChatProperties;
import com.itboy.system.mapper.WeChatUserMapper;
import com.itboy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.itboy.common.constant.Constants.LOGIN_FLAG_COMPUTER;
import static com.itboy.common.constant.Constants.LOGIN_FLAG_WECHAT;
import static com.itboy.common.constant.UserConstants.LOGIN_TYPE;

/**
 * 用户验证处理
 *
 * @author itboy
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private ISysUserService userService;

	@Autowired
	private SysPermissionService permissionService;

	@Autowired
	private WeChatUserMapper weChatUserMapper;

	@Autowired
	private WeChatProperties weChatProperties;


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		// 获取request
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		// 获取头信息
		String loginType = request.getHeader(LOGIN_TYPE);
		if (StrUtil.equals(loginType,LOGIN_FLAG_WECHAT)) {
			// 查询数据库  如果没有直接就注册了
			String wxStr = HttpUtil.get(weChatProperties.getAuthUrl(username));
			JSONObject wxJson = JSONUtil.parseObj(wxStr);
			String openid = wxJson.get("openid").toString();

			WeChatUser weChatUser = weChatUserMapper.selectById(openid);
			if (ObjectUtils.isEmpty(weChatUser)) {
				// 注册
				weChatUser = createWxUser(openid);
			}
			SysUser sysUser = new SysUser();
			sysUser.setUserName(weChatUser.getUserId());
			sysUser.setPassword(weChatUser.getPassword());
			return createLoginUser(sysUser);

		}else{
			SysUser user = userService.selectUserByUserName(username);
			if (Validator.isNull(user)) {
				log.info("登录用户：{} 不存在.", username);
				throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
			} else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
				log.info("登录用户：{} 已被删除.", username);
				throw new BaseException("对不起，您的账号：" + username + " 已被删除");
			} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
				log.info("登录用户：{} 已被停用.", username);
				throw new BaseException("对不起，您的账号：" + username + " 已停用");
			}
			return createLoginUser(user);
		}

	}

	/**
	 * 添加微信用户
	 * @param openid
	 * @return
	 */
	public WeChatUser createWxUser(String openid) {
		WeChatUser weChatUser = new WeChatUser();
		weChatUser.setUserId(openid);
		weChatUser.setStatus(1);
		weChatUserMapper.insert(weChatUser);
		return weChatUser;
	}


	public UserDetails createLoginUser(SysUser user) {
		return new LoginUser(user, permissionService.getMenuPermission(user));
	}


}
